package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询商铺缓存
     * @param id 商铺ID
     */
    @Override
    public Result queryById(Long id) {
        // 解决缓存穿透
        //Shop = queryShopPassThrough(id);

        // 互斥锁解决缓存击穿
        Shop shop = queryWithMutex(id);

        // 逻辑过期解决缓存击穿
//        Shop = queryWithLogical(id);

        return Result.ok(shop);
    }

    /**
     * 解决缓存穿透
     * @param id
     * @return
     */
    public Shop queryShopPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 1. 从 redis 中查询商铺信息
        Map<Object, Object> shopMap = stringRedisTemplate.opsForHash().entries(key);

        // 2. 判断是否存在缓存
        if (!shopMap.isEmpty()) {
            // 3. 存在缓存，直接反序列化为 Shop 对象返回
            Shop shop = BeanUtil.fillBeanWithMap(shopMap, new Shop(), false);
            return shop;
        }

        // 3. 判断是否缓存了空值（防止缓存穿透）
        // 这里我们单独存一个 “空标志” key，例如 cache:shop:null:1
        String nullKey = key + ":null";
        Boolean isNullCached = stringRedisTemplate.hasKey(nullKey);
        if (Boolean.TRUE.equals(isNullCached)) {
            return null;
        }
        // 4. 不存在缓存，从数据库查询
        Shop shop = getById(id);
        // 判断商铺是否存在，不存在就把空值写入 redis
        if (shop == null) {
            stringRedisTemplate.opsForValue().set(nullKey, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        // 5. 将数据库中的店铺信息写入 Redis
        Map<String, Object> shopRedisMap = BeanUtil.beanToMap(
                shop,
                new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) ->
                                fieldValue == null ? null : fieldValue.toString())
        );

        stringRedisTemplate.opsForHash().putAll(CACHE_SHOP_KEY + id, shopRedisMap);
        // 设置缓存过期时间
        stringRedisTemplate.expire(CACHE_SHOP_KEY + id, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return shop;
    }

    /**
     * 解决缓存击穿的查询逻辑（使用互斥锁）
     * @param id 商铺id
     * @return Shop 对象
     */
    private Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 1. 从 Redis 查询缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 2. 判断缓存是否命中
        if (StrUtil.isNotBlank(shopJson)) {
            // 命中缓存
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        // 3. 判断是否是缓存的空值（防止穿透）
        if (shopJson != null) {
            // shopJson == "" 表示缓存了空值
            return null;
        }
        // 4. 实现缓存重建（加互斥锁）
        Shop shop = null;
        String lockKey = LOCK_SHOP_KEY + id;
        try {
            // 4.1 获取互斥锁
            boolean isLock = tryLock(lockKey);
            // 4.2 判断锁是否获取成功
            if (!isLock) {
                // 获取锁失败，休眠50ms再重试
                Thread.sleep(50);
                return queryWithMutex(id); // 递归重试（轻量）
            }
            // ====== 获取锁成功 ======
            // 4.3 Double Check：再次检查缓存是否存在（避免重复重建）
            shopJson = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(shopJson)) {
                return JSONUtil.toBean(shopJson, Shop.class);
            }
            if (shopJson != null) {
                return null;
            }
            // 4.4 缓存中确实没有 → 查询数据库
            shop = getById(id);
            // 4.5 模拟数据库为空 → 写空值防止穿透
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(key, "", 2, TimeUnit.MINUTES);
                return null;
            }
            // 4.6 数据库存在 → 写入缓存
            stringRedisTemplate.opsForValue()
                    .set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 5. 释放锁
            freeLock(lockKey);
        }

        // 6. 返回数据
        return shop;
    }

    // 创建十个线程
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 逻辑锁解决缓存击穿
     * @param id
     * @return
     */
    private Shop queryWithLogical(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 1. 从 Redis 查询缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 2. 判断缓存是否存在
        if (StrUtil.isBlank(shopJson)) {
            // 缓存不存在，说明未预热，直接返回 null 或查数据库
            return null;
        }
        // 3. 命中缓存，反序列化 RedisData
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        // 注意：这里 data 是 Object 类型，需要强转或再反序列化
        JSONObject dataJson = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(dataJson, Shop.class);

        LocalDateTime expireTime = redisData.getExpireTime();

        // 4. 判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            // 4.1 未过期，直接返回
            return shop;
        }

        // 5. 已过期则缓存重建
        // 5.1. 尝试获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        // 6. 判断是否能获取互斥锁
        if (isLock) {
            // 获取锁成功，开启异步线程重建缓存
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    saveShopToRedis(id, 300L); // 逻辑过期时间（秒）
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    freeLock(lockKey);
                }
            });
        }

        // 6. 无论是否过期，先返回旧数据（保证可读）
        return shop;
    }


    /**
     * 获取锁
     * @param key
     * @return
     */
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);  // 避免自动拆箱出现空指针异常
    }

    /**
     * 释放锁
     * @param key
     */
    private void freeLock(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 店铺数据预热到 Redis（带逻辑过期时间）
     */
    public void saveShopToRedis(Long id, Long expireSeconds) {
        String key = CACHE_SHOP_KEY + id;

        // 1. 查询数据库
        Shop shop = getById(id);
        if (shop == null) {
            return;
        }

        // 2. 封装逻辑过期对象
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));

        // 3. 写入 Redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 更新店铺信息
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if(id == null) {
            return Result.fail("店铺id不能为空");
        }
        // 更新数据库
        updateById(shop);
        // 删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);

        return Result.ok();
    }

    /**
     * 展示附近店铺
     * @param typeId
     * @param current
     * @param x
     * @param y
     * @return
     */
    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 判断是否需要根据坐标查询
        if(x == null || y == null) {
            Page<Shop> page = query().eq("type_id", typeId).page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }
        // 根据页码计算分页参数
        int begin = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        // 查询 Redis 获得 shopId 与 距离  GEOSEARCH key [FROMMEMBER] [FROMLONLAT longitude latitude][COUNT count [ANY]]WITHDIST
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );
        // 解析出 id
        if(results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if(list.size() <= begin) {
            // 没有下一页，结束
            return Result.ok(Collections.emptyList());
        }
        // 截取 form ~ end 的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(begin).forEach(result -> {
            // 获取店铺 id
            String shopId = result.getContent().getName();
            ids.add(Long.valueOf(shopId));
            // 获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopId, distance);
        });
        // 根据 id 查询店铺
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }

        return Result.ok(shops);
    }
}
